import store from '@/store/index.js'
export class AppSharePopup {
	shareInfo = {};
	actionList = [];
	alphaBg = null;
	menuPopup = null;
	cancelText = '取消分享';
	platformShareList = [];

	otherShareList = [{
			icon: "/static/images/share/copy.png",
			text: "复制",
			provider: "copy",
			onClick: this.onCopy
		},
		{
			icon: "/static/images/share/more.png",
			text: "更多",
			provider: "more",
			onClick: this.onMore
		}
	];
	constructor(arg = {}) {
		this.actionList = arg.actionList || [];
		this.cancelText = arg.cancelText || (this.actionList.length > 0 ? '取消' : '取消分享');
		this.setShareInfo(arg.shareInfo || {});
	}



	hide() {
		this.alphaBg && this.alphaBg.close();
		this.menuPopup && this.menuPopup.close();
		this.alphaBg = null;
		this.menuPopup = null;
	}

	onCopy(item, shareInfo, callback = null) {
		let copyText = '穗穗婚恋幸福之门已打开，快进来看看吧!→→→' + shareInfo.shareUrl || shareInfo.shareContent || shareInfo.shareImg;
		if (copyText) {
			uni.setClipboardData({
				data: copyText,
				success: () => {
					uni.showToast({
						title: "已复制到剪贴板",
						icon: "none"
					});
					callback && callback(item);
				}
			});
		}
	}

	onMore(item, shareInfo, callback = null) {
		plus.share.sendWithSystem({
			type: "text",
			title: shareInfo.shareTitle || "",
			href: shareInfo.shareUrl || "",
			content: shareInfo.shareContent || "",
		}, (res) => {
			callback && callback(item);
		});
	}

	onShare(item, shareInfo, callback = null) {
		if (shareInfo.type == undefined) {
			shareInfo.type = item.type;
		}
		let shareObj = {
			provider: item.provider,
			type: shareInfo.type,
			success: (res) => {
				uni.hideLoading()
				uni.showToast({
					title: "分享成功"
				});
				callback && callback(item);
				console.log("success:" + JSON.stringify(res));
			},
			fail: (err) => {
				uni.hideLoading()
				console.log("分享失败，参数缺失 fail:" + JSON.stringify(err));
			}


		};
		if (shareInfo.shareTitle) {
			shareObj.title = shareInfo.shareTitle;
		} else if (item.provider == "qq") {
			uni.showToast({
				title: "缺失分享的标题",
				icon: "none"
			});
			return;
		}
		if (shareInfo.type == 0 || item.provider == "qq") {
			if (shareInfo.shareUrl) {
				shareObj.href = shareInfo.shareUrl;
			} else {
				uni.showToast({
					title: "缺失分享的地址",
					icon: "none"
				});
				return;
			}
		}
		if ([0, 1, 3, 4].includes(shareInfo.type)) {
			if (shareInfo.shareContent) {
				shareObj.summary = shareInfo.shareContent;
			} else {
				uni.showToast({
					title: "缺失分享的描述",
					icon: "none"
				});
				return;
			}
		}
		if ([0, 2, 5].includes(shareInfo.type)) {

			if (shareInfo.shareImg) {
				shareObj.imageUrl = shareInfo.shareImg;
			} else {
				uni.showToast({
					title: "缺失分享的图片",
					icon: "none"
				});
				return;
			}
		}
		if ([3, 4].includes(shareInfo.type)) {
			if (shareInfo.mediaUrl) {
				shareObj.mediaUrl = shareInfo.mediaUrl;
			} else {
				uni.showToast({
					title: "缺失分享的音视频地址",
					icon: "none"
				});
				return;
			}
		}
		if (shareInfo.type == 5) {
			if (shareInfo.appId && shareInfo.appPath && shareInfo.shareUrl) {
				shareObj.miniProgram = {
					id: shareInfo.appId,
					path: shareInfo.appPath,
					webUrl: shareInfo.shareUrl,
				};
				if (shareInfo.appType) {
					shareObj.miniProgram.type = shareInfo.appType;
				}
			} else {
				uni.showToast({
					title: "缺失分享小程序的参数",
					icon: "none"
				});
				return;
			}
		}

		if (item.scene) {
			shareObj.scene = item.scene;
		}
		uni.showLoading({
			title: '请求分享',
			mask: true
		})
		uni.share(shareObj);
		setTimeout(() => {
			uni.hideLoading()
		}, 3000)
	}
	//从缓存中获取分享平台列表并处理
	getSharePlatform() {
		const shareServiceProvider = store.state.cache.shareServiceProvider;
		const sharePlatformList = [];

		if (shareServiceProvider.includes('weixin')) {
			sharePlatformList.push(...[{
					icon: "/static/images/share/wx.png",
					text: "微信好友",
					onClick: this.onShare,
					provider: "weixin",
					scene: "WXSceneSession",
					type: 0
				},
				{
					icon: "/static/images/share/pyq.png",
					text: "朋友圈",
					onClick: this.onShare,
					provider: "weixin",
					scene: "WXSenceTimeline",
					type: 0
				},
				{
					icon: "/static/images/share/mp.png",
					text: "小程序",
					onClick: this.onShare,
					provider: "weixin",
					scene: "WXSceneSession",
					type: 5
				}
			])
		}
		if (shareServiceProvider.includes('sinaweibo')) {
			sharePlatformList.push({
				icon: "/static/images/share/weibo.png",
				text: "新浪微博",
				onClick: this.onShare,
				provider: "sinaweibo",
				type: 0
			})
		}
		if (shareServiceProvider.includes('qq')) {
			sharePlatformList.push({
				icon: "/static/images/share/qq.png",
				text: "QQ",
				onClick: this.onShare,
				provider: "qq",
				type: 1
			})
		}
		return sharePlatformList
	}
	// 过滤分享平台的方法
	platformFilter(sharePlatformList) {
		const data = sharePlatformList.concat(this.otherShareList);
		const list = []

		if (!(this.shareInfo.appId && this.shareInfo.appPath)) {
			data.map(item => {
				if (item.type != 5) {
					list.push(item)
				}
			})
			return list
		}
		return data;
	}
	//设置分享信息
	setShareInfo(data = {}) {
		const shareInfo = {};
		shareInfo.shareTitle = data.share_title || '';
		shareInfo.shareUrl = data.share_url || '';
		shareInfo.shareContent = data.share_brief || '';
		shareInfo.shareImg = data.share_image || ''
		shareInfo.appPath = data.share_path + '?' + data.share_query
		shareInfo.appId = 'wxb83bd994e9b8ac76';
		shareInfo.appType = data.share_type || 0;
		this.shareInfo = shareInfo;
	}

	//展示弹窗
	show(callback = null) {
		let screenWidth = plus.screen.resolutionWidth;
		//更新 考虑一排放置6个，故colNumber为6
		let colNumber = 6;
		if (screenWidth < 375) {
			//如果小于ip6，排放置5个
			colNumber = colNumber - 1
		}
		const popupTop = 10;
		const itemWidth = screenWidth / colNumber; //计算每个项目的宽度
		const itemPadding = 10; //定义项目内边距
		const iconSize = itemWidth - 2 * itemPadding; //计算项目图标尺寸
		const iconTextSize = 12; //定义图标文字大小
		const iconTextSpace = 10; //定义图标文字间隙
		const itemHeight = itemWidth + iconTextSize + iconTextSpace; //计算每个项目的高度
		const closeBtnHeight = 50;

		let shareList = this.platformFilter(this.getSharePlatform());
		//开始计算菜单的高度
		const sharePartRow = Math.ceil(shareList.length / colNumber); // 计算分享部分行数
		const actionPartRow = Math.ceil(this.actionList.length / colNumber); // 计算交互部分行数
		const sharePartHeight = sharePartRow * itemHeight; //计算分享部分高度
		const actionPartHeight = actionPartRow * itemHeight; //计算交互部分高度
		const actionPartMarginTop = sharePartHeight + popupTop + 1; //计算交互部分初始高度


		const alphaBg = new plus.nativeObj.View("alphaBg", { //先创建遮罩层
			top: '0px',
			left: '0px',
			height: '100%',
			width: '100%',
			backgroundColor: 'rgba(0,0,0,0.5)'
		});
		alphaBg.addEventListener("click", function() { //处理遮罩层点击
			alphaBg.close();
			menuPopup.close();
		});
		// const sharePartHeight = Math.ceil(shareList.length / colNumber) * itemHeight + margin * 2;
		// const actionPartheight = Math.ceil(shareInfo.actionList.length / colNumber) * itemHeight + margin * 2;
		const menuPopup = new plus.nativeObj.View("menuPopup", { //创建底部图标菜单
			bottom: '0px',
			left: '0px',
			height: sharePartHeight + actionPartHeight + 1 + 1 + closeBtnHeight + popupTop + 'px',
			width: '100%',
			backgroundColor: 'rgb(255,255,255)'
		});
		//绘制底部图标菜单的内容
		menuPopup.draw([{
				tag: 'rect', //菜单顶部的分割灰线
				color: '#e7e7e7',
				position: {
					top: '0px',
					height: '1px'
				}
			},
			{
				tag: 'font',
				id: 'sharecancel', //底部取消按钮的文字
				text: this.cancelText,
				textStyles: {
					size: '14px'
				},
				position: {
					bottom: '0px',
					height: closeBtnHeight + 'px'
				}
			},
			{
				tag: 'rect', //底部取消按钮的顶部边线
				color: '#e7e7e7',
				position: {
					bottom: closeBtnHeight + 1 + 'px',
					height: '1px'
				}
			}
		]);
		shareList.map((v, k) => {
			let time = new Date().getTime();
			let row = Math.floor(k / colNumber);
			let col = k % colNumber;
			let item = [{
					src: v.icon,
					id: Math.random() * 1000 + time,
					tag: "img",
					position: {
						top: row * itemHeight + popupTop + itemPadding,
						left: col * itemWidth + itemPadding,
						width: iconSize,
						height: iconSize
					}
				}, {
					text: v.text,
					id: Math.random() * 1000 + time,
					tag: "font",
					textStyles: {
						size: iconTextSize
					},
					position: {
						top: row * itemHeight + iconTextSpace + popupTop + iconSize + itemPadding,
						left: col * itemWidth + itemPadding,
						width: iconSize,
						height: iconTextSize
					}
				},

			];
			menuPopup.draw(item);
		});
		menuPopup.draw([{
			tag: 'rect', //菜单顶部的分割灰线
			color: '#e7e7e7',
			position: {
				top: sharePartHeight + popupTop + 1,
				height: '1px',
				left: itemPadding + 'px',
				right: itemPadding + 'px',
			}
		}])
		this.actionList.map((v, k) => {
			let time = new Date().getTime();
			let row = Math.floor(k / colNumber);
			let col = k % colNumber;
			let item = [{
				src: v.icon,
				id: Math.random() * 1000 + time,
				tag: "img",
				position: {
					top: row * itemHeight + itemPadding + actionPartMarginTop,
					left: col * itemWidth + itemPadding,
					width: iconSize,
					height: iconSize
				}
			}, {
				text: v.text,
				id: Math.random() * 1000 + time,
				tag: "font",
				textStyles: {
					size: iconTextSize
				},
				position: {
					top: row * itemHeight + iconTextSpace + iconSize + itemPadding + actionPartMarginTop,
					left: col * itemWidth + itemPadding,
					width: iconSize,
					height: iconTextSize
				}
			}];
			menuPopup.draw(item);
		})

		menuPopup.addEventListener("click", (e) => { //处理底部图标菜单的点击事件，根据点击位置触发不同的逻辑
			if (e.screenY > plus.screen.resolutionHeight - (closeBtnHeight + 1)) { //点击了底部取消按钮
				alphaBg.close();
				menuPopup.close();
			} else { //点击了图标按钮
				let mapping = ''
				let x = e.clientX;
				let y = e.clientY;

				if (y > popupTop && y <= sharePartHeight) {
					mapping = 'shareList';
				} else if (y > actionPartMarginTop) {
					mapping = 'actionList';
					y = y - actionPartMarginTop;
				}
				let colIdx = Math.floor(x / itemWidth);
				let rowIdx = Math.floor(y / itemHeight);
				let tapIndex = colIdx + rowIdx * colNumber;
				if (mapping == 'shareList') {
					console.log(this.shareInfo)
					shareList[tapIndex].onClick(shareList[tapIndex], this.shareInfo, callback);
				} else {
					this[mapping][tapIndex].onClick(this[mapping][tapIndex]);
				}
				this.hide()
			}
		});

		alphaBg.show();
		menuPopup.show();
		this.alphaBg = alphaBg;
		this.menuPopup = menuPopup;
	}
}
